<template>
  <div class="app-container">
    <div class="filter-container">
        <el-input clearable v-model="search.name" placeholder="名称" style="width: 170px;"></el-input>
        <!-- <el-select v-model="search.type" clearable placeholder="类型" style="width: 130px; margin-left:10px;">
            <el-option 
            v-for="(item,index) in selectOptions.bannerTypes"
            :key="index"
            :label="item.label"
            :value="item.value">
            </el-option>
        </el-select> -->
        
        <el-button type="primary" icon="el-icon-search" @click="searchClick()" style="margin-left:10px;">查询</el-button>
        <el-button type="success" icon="el-icon-folder-add" @click="handleAdd()" >新增</el-button>
    </div>
    <el-table v-loading="listLoading" :data="list"  border fit highlight-current-row stripe  style="width: 100%">
      <el-table-column align="center" label="序" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row._id }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="排序">
        <template slot-scope="scope">
          <span>{{scope.row.sort}}</span>
        </template>
      </el-table-column>
      
      <el-table-column  min-width="20%" label="图片" align="center">
        <template slot-scope="scope">
            <span>
              <span>
                <el-image  style="width: 225px; height: 100px" :src="scope.row.imageConvert"  :preview-src-list="scope.row.imagePreviews">
                </el-image>
              </span>
            </span>
        </template>
      </el-table-column>
      <el-table-column  min-width="10%" align="center" label="名称">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column min-width="10%" align="center" label="类型">
        <template slot-scope="scope">
          <span>{{scope.row.type | parseBannerTypes}}</span>
        </template>
      </el-table-column>
      <el-table-column  min-width="10%" align="center" label="时间">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作"  min-width="10%">
        <template slot-scope="scope">
            <el-popconfirm title="确定要删除这条记录吗？" icon="el-icon-info"  icon-color="red"  @onConfirm="handleDelete(scope.row.id)" >
              <el-button slot="reference" type="danger" size="small" icon="el-icon-delete" style="margin-left:5px;" >
                  删除
              </el-button>
            </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.rows" @pagination="getList" />

    <el-dialog title="新增Banner图片" :visible.sync="dialog.visible"  width="700px">
        <div class="ci">
          <div class="item">
            <span class="name required">排序</span>
            <span class="value">
              <!-- <el-input clearable type="number" v-model="dialog.data.sort" :min="0" :max="99999" ></el-input> -->
              <el-input-number v-model="dialog.data.sort" controls-position="right" :min="0" :max="99999" placeholder="值越大则排序靠前"></el-input-number>
              <span style="margin-left:10px;">值越大则排序靠前</span>
            </span>
          </div>
          
          
          <div class="item">
            <span class="name required">类型</span>
            <span class="value">
              <el-select v-model="dialog.data.type" clearable placeholder="类型" style="width: 200px; ">
                <el-option 
                v-for="(item,index) in selectOptions.bannerTypes"
                :key="index"
                :label="item.label"
                :value="item.value">
                </el-option>
            </el-select>
            </span>
          </div>
          <div class="item">
            <span class="name required">名称</span>
            <span class="value">
              <el-input clearable  v-model="dialog.data.name" maxlength="100"  placeholder="图片的说明" style="width: 100%;"></el-input>
            </span>
          </div>
          <div class="item h100">
            <span class="name required">图片</span>
            <span class="value pics">
                 <div class="pic" v-show="dialog.imgConvert.length>0">
                  <bx-image :src="dialog.imgConvert" :width="80" :height="80" :show-delete="true" @delete-handler="bannerFileDeleteHandle"></bx-image>
                </div>
                <div class="upload-box" @click="clickUploadBannerFile()" v-show="dialog.imgConvert.length==0">
                   <i class="el-icon-plus avatar-uploader-icon"></i>
                   <input ref="selectfileForBanner" type="file" style="display:none;" @change="selectFileBanner($event)" />
                </div>
            </span>
          </div>
          
        </div>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialog.visible = false">取 消</el-button>
            <el-button type="primary" @click="saveNewBanner()" :loading="dialog.saveloading">确 定</el-button>
        </div>
    </el-dialog>

  </div>
</template>

<script>

import { deepClone,parseTime } from '@/utils'
import * as auth from '@/utils/auth'
import * as appdataApi from '@/api/appdata'
import * as uploadApi from '@/api/upload'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import BxImage from '@/components/BxImage'
import * as imageHelper from '@/utils/image'
import * as enumHelper from '@/utils/enum'
import * as fileUpload from '@/utils/fileupload'
import guid from '@/utils/guid'

export default {
  name: 'BannerManage',
  components: { Pagination,BxImage },
  data(){
    return{
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        rows: 20,
        // type:'',
        name:'',
      },
      search:{
        type:'',
        name:'',
      },
      selectOptions:{
         bannerTypes:[
           {label:'Banner',value:'1'},
         ]
      },
      dialog:{
          visible:false,
          saveloading:false,
          imgConvert:'',
          //数据
          data:{
            sort:'',
            name:'',
            img:'',
            
            type:'1'
          }
      },
      upload:{
        token:'',
        pictrues:{
          running:false,
          percent:0,
          state:0,
          previewing:false
        }
      }
    }
  },
  created(){
      var that=this;
      that.getList();
      //that.selectOptions.client=[];
      // Object.values(enumHelper.system.mobileClient).map(v=>{
      //   if(typeof(v)!='number'){return;}
      //   that.selectOptions.client.push({label:enumHelper.system.mobileClient.getName(v),value:v});
      // })
      //加载上传token
      uploadApi.GetUploadToken(1).then(res=>{
          that.upload.token=res.data.token;
      });
  },
  mounted(){
  },
  filters:{
    parseBannerTypes(val){
        return ['','Banner',''][val];
    }
  },
  methods: {
   
    getList(){
      var that=this;
      that.listLoading = true;
      //that.listQuery.name=that.search.name;
      //that.listQuery.type=that.search.type;
      appdataApi.getAppBannerList(that.listQuery).then(res=>{
         if(res.data){
            that.list=[...res.data.items.map((item,index)=>{
              item._id=index+1;
              
              item.imageConvert=imageHelper.GetFullUrl(item.image,700,700);
              item.imagePreviews=[item.imageConvert];
              return item;
            })];
            that.listLoading = false;
            that.total=res.data.total || 0;
         }
      })
    },

    searchClick(){
      var that=this;
      that.listQuery.page=1;
      that.listQuery.name=that.search.name.trim();
      that.getList();
    },
    handleAdd(){
      this.dialog.visible=true;
    },
    
    saveNewBanner(){
        var that=this;
        
        //check data 
        if(!that.checkNewBannnerData(that.dialog.data)){
          return;
        }
        that.dialog.saveloading=true;
        appdataApi.addNewBanner(that.dialog.data).then(res=>{
            if(res.data){
                that.$message({
                    message: '保存成功！',
                    type: 'success'
                });
                
                that.dialog.saveloading=false;
                that.dialog.visible=false;
                that.getList();
            }
        })
    },
    checkNewBannnerData(data){
      var that=this;
        var errorMsg=[];
        if(!data.sort){
            errorMsg.push('请填写序号');
        }
        if(!data.name.trim()){
            errorMsg.push('请填写名称');
        }
        if(!data.type){
            errorMsg.push('请选择类型');
        }
        if(!data.img){
            errorMsg.push('请上传图片');
        }
        
        if(errorMsg.length>0){
          var errorHtml='<p class="errorbox-item">'+errorMsg.join('</p><p class="errorbox-item">')+'</p>';
          that.$notify({
            title: '验证未通过',
            dangerouslyUseHTMLString: true,
            position: 'bottom-left',
            message: errorHtml
          });
          return false;
        }
        return true;
    },
    handleDelete(id){
      var that=this;
       appdataApi.deleteBanner({id:id}).then(res=>{
          if(res.data){
            that.$message({
              message: '删除成功',
              type: 'success'
            });
            setTimeout(()=>{
                var idx=that.list.findIndex(item=>item.id==id);
                if(idx>-1){
                  that.list.splice(idx,1);
                }
            },500)
            
          }
       })
    },

    //上传课程宣传图片
    clickUploadBannerFile(){
      var that=this;
      
      if(that.upload.pictrues.running){
        that.$message({
          message: '当前正在上传中',
          type: 'warning'
        });
        return;
      }
      that.$refs.selectfileForBanner.dispatchEvent(new MouseEvent('click'))
    },
    selectFileBanner($event){
      var that=this;
      var token=that.upload.token;
      var key=guid.createGuid().replace(/-/g,'')+".jpg";

       var files=$event.target.files;
       if(files.length==0){return;}
       that.upload.pictrues.running=true;
       that.upload.pictrues.percent=0;

      fileUpload.uploadQiniu({
          file:files[0],
          token:token,
          key:key,
          process:function(percert){
            console.log('正在上传...'+percert.toFixed(2)+'%');
          }
       }).then(completeres=>{

          that.dialog.data.img=completeres.key;
          that.dialog.imgConvert=imageHelper.GetFullUrl(completeres.key,200,200);


          that.upload.pictrues.state=1;
          that.upload.pictrues.previewing=true;
          that.upload.pictrues.percent=100;
          setTimeout(function(){
              that.upload.pictrues.running=false;
            },1000)
       }).catch(err=>{
          that.upload.pictrues.state=2;
          that.upload.pictrues.running=false;
          that.$message({
            message: err,
            type: 'danger'
          });
       })



      
    },
    //删除图片
    bannerFileDeleteHandle(){
      var that=this;
       that.dialog.img='';
       that.dialog.imgConvert='';
       that.$refs.selectfileForBanner.value='';
       
    },
  }
}
</script>
<style scoped>
table.table{ table-layout: fixed;}
 table.table>tr:nth-child(2){
    background: #f1f1f1;
 }
 table.table>tr:nth-child(3){
    background: #e1e1e1;
 }
 table.table>tr>td{text-align: center;}
</style>
